﻿using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.RBAC;
using System;
using System.Collections.Generic;

namespace ThridGroup.ERP.Web.Controllers
{
    /// <summary>
    /// 角色权限控制器
    /// </summary>
    [Route("RolePermission/[action]")]
    public class RolePermissionController : Controller
    {
        private readonly IRolePermissionServices _rolePermissionService;

        public RolePermissionController(IRolePermissionServices rolePermissionService)
        {
            _rolePermissionService = rolePermissionService;
        }

        /// <summary>
        ///角色权限管理
        /// </summary>
        /// <returns></returns>
        public IActionResult RolePermissionView()
        {
            return View();
        }
        /// <summary>
        /// 添加角色权限
        /// </summary>
        /// <param name="createRolePermissionDto">角色权限信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddRolePermission([FromBody] CreateRolePermissionDto createRolePermissionDto)
        {
            try
            {
                // 添加详细的调试日志
                Console.WriteLine("=== AddRolePermission 开始 ===");
                Console.WriteLine($"接收到的数据: createRolePermissionDto = {(createRolePermissionDto == null ? "null" : "not null")}");
                
                if (createRolePermissionDto != null)
                {
                    Console.WriteLine($"RoleId: {createRolePermissionDto.RoleId}");
                    Console.WriteLine($"PermissionId: {(createRolePermissionDto.PermissionId == null ? "null" : $"Count={createRolePermissionDto.PermissionId.Count}")}");
                    if (createRolePermissionDto.PermissionId != null)
                    {
                        Console.WriteLine($"PermissionId内容: [{string.Join(", ", createRolePermissionDto.PermissionId)}]");
                    }
                }
                
                // 验证模型
                Console.WriteLine($"ModelState.IsValid: {ModelState.IsValid}");
                if (!ModelState.IsValid)
                {
                    Console.WriteLine("模型验证失败:");
                    foreach (var error in ModelState)
                    {
                        Console.WriteLine($"  {error.Key}: {string.Join(", ", error.Value.Errors.Select(e => e.ErrorMessage))}");
                    }
                    return BadRequest(new { success = false, message = "数据验证失败", errors = ModelState });
                }
                
                if (createRolePermissionDto == null)
                {
                    Console.WriteLine("请求数据为空");
                    return BadRequest(new { success = false, message = "请求数据为空" });
                }
                
                Console.WriteLine("开始调用服务层方法");
                var result = await _rolePermissionService.AddRolePermission(createRolePermissionDto);
                Console.WriteLine($"服务层返回结果: {result}");
                
                if (result == 1)
                {
                    Console.WriteLine("添加成功");
                    return Ok(new { success = true, message = "添加成功", data = result });
                }
                else
                {
                    Console.WriteLine("添加失败");
                    return BadRequest(new { success = false, message = "添加失败，请检查数据是否有效" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常发生: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 记录异常日志
                return StatusCode(500, new { success = false, message = "服务器内部错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryRole()
        {
            var roles = await _rolePermissionService.QueryRole();
            return Json(new
            {
                code = 0,
                msg = "",
                count = roles.Count,
                data = roles
            });
        }


        /// <summary>
        /// 查询所有权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryPermission()
        {
            var permissions = await _rolePermissionService.QueryPermission();
            return Json(new
            {
                code = 0,
                msg = "",
                count = permissions.Count,
                data = permissions
            });
        }



        /// <summary>
        /// 连表查询角色、权限和角色权限，兼容Layui分页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryRolePermission(int page = 1, int limit = 10)
        {
            var rolePermissions = await _rolePermissionService.QueryRolePermission();
            var data = rolePermissions.Skip((page - 1) * limit).Take(limit).ToList();
            return Json(new
            {
                code = 0,
                msg = "",
                count = rolePermissions.Count,
                data = data
            });
        }



        /// <summary>
        /// 删除角色权限
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteRolePermission(int id)
        {
            await _rolePermissionService.DeleteRolePermission(id);
            return Json(new { success = true, message = "删除成功" });
        }

        /// <summary>
        /// 获取角色的所有权限（用于反填）
        /// </summary>
        /// <param name="roleIds">角色Ids</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetRolePermission([FromQuery] List<int> roleIds)
        {
            var data = await _rolePermissionService.GetRolePermission(roleIds);
            return Json(new { success = true, data });
        }

        /// <summary>
        /// 获取单个角色的所有权限（用于反填）
        /// </summary>
        /// <param name="roleId">角色Id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetRolePermissionByRoleId([FromQuery] int roleId)
        {
            var roleIds = new List<int> { roleId };
            var dataList = await _rolePermissionService.GetRolePermission(roleIds);
            var data = dataList.FirstOrDefault();
            return Json(new { success = true, data });
        }

        /// <summary>
        /// 修改角色权限信息
        /// </summary>
        /// <param name="createRoleDto">角色权限信息</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateRolePermission([FromBody] CreateRolePermissionDto createRoleDto)
        {
            try
            {
                // 修改详细的调试日志
                Console.WriteLine("=== UpdateRolePermission 开始 ===");
                Console.WriteLine($"接收到的数据: createRolePermissionDto = {(createRoleDto == null ? "null" : "not null")}");

                if (createRoleDto != null)
                {
                    Console.WriteLine($"RoleId: {createRoleDto.RoleId}");
                    Console.WriteLine($"PermissionId: {(createRoleDto.PermissionId == null ? "null" : $"Count={createRoleDto.PermissionId.Count}")}");
                    if (createRoleDto.PermissionId != null)
                    {
                        Console.WriteLine($"PermissionId内容: [{string.Join(", ", createRoleDto.PermissionId)}]");
                    }
                }

                // 验证模型
                Console.WriteLine($"ModelState.IsValid: {ModelState.IsValid}");
                if (!ModelState.IsValid)
                {
                    Console.WriteLine("模型验证失败:");
                    foreach (var error in ModelState)
                    {
                        Console.WriteLine($"  {error.Key}: {string.Join(", ", error.Value.Errors.Select(e => e.ErrorMessage))}");
                    }
                    return BadRequest(new { success = false, message = "数据验证失败", errors = ModelState });
                }

                if (createRoleDto == null)
                {
                    Console.WriteLine("请求数据为空");
                    return BadRequest(new { success = false, message = "请求数据为空" });
                }

                Console.WriteLine("开始调用服务层方法");
                var result = await _rolePermissionService.AddRolePermission(createRoleDto);
                Console.WriteLine($"服务层返回结果: {result}");

                if (result == 1)
                {
                    Console.WriteLine("修改成功");
                    return Ok(new { success = true, message = "修改成功", data = result });
                }
                else
                {
                    Console.WriteLine("修改失败");
                    return BadRequest(new { success = false, message = "修改失败，请检查数据是否有效" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"异常发生: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                // 记录异常日志
                return StatusCode(500, new { success = false, message = "服务器内部错误", error = ex.Message });
            }
        }

        /// <summary>
        /// 获取角色权限树
        /// </summary>
        /// <returns>角色权限树结构</returns>
        [HttpGet]
        public async Task<IActionResult> GetRolePermissionTree()
        {
            try
            {
                Console.WriteLine("=== GetRolePermissionTree 开始 ===");
                var result = await _rolePermissionService.QueryRolePermissionTree();
                Console.WriteLine($"获取到权限树数据条数: {result?.Count ?? 0}");
                return Json(new { code = 0, msg = "success", data = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取角色权限树异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                return Json(new { code = 1, msg = "获取角色权限树失败: " + ex.Message });
            }
        }





    }
}
